package search;

/**
 * Created by Tzachi on 18/10/2014.
 */
public class BinarySearch {

    // return index of element or -1
    public static int recursive_search(int[] a, int target, int lowIndex, int highIndex) {
        int middleIndex = lowIndex + (highIndex - lowIndex) / 2;
        if (a[middleIndex] == target) {
            return middleIndex;
        }
        // item not found
        if (highIndex - lowIndex == 0) {
            return -1;
        }
        if (target < a[middleIndex]) {
            return recursive_search(a, target, lowIndex, middleIndex - 1);
        } else {
            return recursive_search(a, target, middleIndex + 1, highIndex);
        }
    }

    public static void main(String[] args) {
        int[] a = {1, 2, 4, 5, 7, 8, 9};
        System.out.println(recursive_search(a, 8, 0, a.length - 1));
        System.out.println(recursive_search(a, 4, 0, a.length - 1));
        System.out.println(recursive_search(a, 3, 0, a.length - 1));
    }
}
